package com.ts.animal.controller;

import com.ts.animal.constant.AnimalConstant;
import com.ts.animal.service.RfidSyncDataService;
import com.ts.common.enums.ResultCode;
import com.ts.common.redis.RedisUtil;
import com.ts.common.utils.DateUtils;
import com.ts.common.utils.ResponseResult;
import com.ts.common.utils.StringUtils;
import com.ts.common.utils.UtilDate;
import com.ts.system.domain.DeptDO;
import com.ts.system.util.SystemUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/animal/open/api")
public class OpenApiController {

    private static final Logger logger = LoggerFactory.getLogger(OpenApiController.class);
    @Autowired
    private RfidSyncDataService rfidSyncDataService;

    @ResponseBody
    @RequestMapping("/baseStationData")
    @ApiOperation("查询基站数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startTime", value = "开始时间 yyyy-MM-dd HH:mm:ss", required = true),
            @ApiImplicitParam(name = "endTime", value = "结束时间 yyyy-MM-dd HH:mm:ss", required = true)
    })
    public ResponseResult baseStationData(HttpServletRequest request, String startTime, String endTime) throws Exception {

        String headerAppId = request.getHeader("appid");
        if (headerAppId == null) {
            return ResponseResult.error().setMsg("appid不可为空");
        } else {
            Integer interval = Integer.valueOf(SystemUtil.getSystemParams().get(AnimalConstant.key_name_open_api_call_interval).getParamValue());
            String repetition = RedisUtil.get(AnimalConstant.REDIS_BASE_OPEN_API_CALL_FLAG_BASESTATIONDATA + headerAppId);
            RedisUtil.set(AnimalConstant.REDIS_BASE_OPEN_API_CALL_FLAG_BASESTATIONDATA + headerAppId, headerAppId, interval, TimeUnit.SECONDS);
            if (StringUtils.isNotEmpty(repetition)) {
                return ResponseResult.error().setCode(ResultCode.FAIL).setMsg("接口请求太频繁，请" + interval + "秒后再次发起请求");
            }

        }
        DeptDO deptDO = SystemUtil.getAppidDepts().get(headerAppId);
        if (deptDO == null) {
            return ResponseResult.error().setMsg("appid不可用");
        }
        long deptId = deptDO.getDeptId();
        if (StringUtils.isAnyEmpty(startTime, endTime)) {
            return ResponseResult.error().setCode(ResultCode.FAIL).setMsg("请输入开始时间和结束时间");
        }
        Date startDateTime = UtilDate.convertDateTimeByFormate(startTime, DateUtils.DATE_TIME_PATTERN);
        Date endDateTime = UtilDate.convertDateTimeByFormate(endTime, DateUtils.DATE_TIME_PATTERN);
        if (startDateTime == null || endDateTime == null) {
            return ResponseResult.error().setCode(ResultCode.FAIL).setMsg("开始时间和结束时间格式错误，时间格式为 yyyy-MM-dd HH:mm:ss");
        }
        Integer limitMinute = Integer.valueOf(SystemUtil.getSystemParams().get(AnimalConstant.key_name_open_api_query_data_collectionTime_limit).getParamValue());
        if ((endDateTime.getTime() - startDateTime.getTime()) / (1000 * 60) > limitMinute) {
            return ResponseResult.error().setCode(ResultCode.FAIL).setMsg("开始时间和结束时间间隔不可以大于" + limitMinute + "分钟");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("deptId", deptId);
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        return ResponseResult.success().setData(rfidSyncDataService.queryBaseStationData(map));
    }

}
